package com.gzxw.mogublog.admin.security;

import com.alibaba.fastjson.JSON;
import com.gzxw.mogublog.commons.config.security.LoginUser;
import com.gzxw.mogublog.utils.R;
import com.gzxw.mogublog.utils.ServletUtils;
import com.gzxw.mogublog.xo.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: mogublog
 * @author: gzxw
 * @create: 2023-04-27 10:39
 **/
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        LoginUser loginUser = tokenService.getLoginUser(httpServletRequest);
        if (loginUser != null) {
            // 删除用户缓存信息
            tokenService.delLoginUser(loginUser.getToken());
        }
        ServletUtils.renderString(response, JSON.toJSONString(R.success("200", "退出成功")));
    }
}
